package com.hzqy.service.content;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hzqy.commons.utils.DeCompressUtil;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.persistence.dao.content.ContentComponentDao;
import com.hzqy.persistence.dao.content.ContentDao;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.vo.CmContentVo;

import static com.hzqy.commons.utils.FileUtil.fileCheck;

@Service
public class ContentComponentServiceBean  extends GenericServiceBean<Object, ContentComponentDao, Integer>{
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Override
	public ContentComponentDao getEntityDao() {
		return contentComponentDao;
	}
	private static final int  BUFFER_SIZE = 2 * 1024;
	@Resource
	private ContentComponentDao contentComponentDao;
	@Resource
	private ContentDao contentDao;

	public void selectContentListDownload(CmContentVo cmContentVo,HttpServletResponse response, HttpServletRequest request,HttpSession session) {
		if(cmContentVo==null||cmContentVo.getF_cc_ids()==null||cmContentVo.getF_cc_ids()==""){
			LOG.error("数据异常。");
			try {
				response.getWriter().print("error");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try{
				List<CmContentVo> list=contentComponentDao.selectContentListDownload(cmContentVo);
				String userAgent = request.getHeader("User-Agent");
				// filename.getBytes("UTF-8")处理safari的乱码问题
				String outPath="contentList.zip";
				byte[] bytes = userAgent.contains("MSIE") ? outPath.getBytes() : outPath.getBytes("UTF-8");
				// 各浏览器基本都支持ISO编码
				outPath = new String(bytes, "ISO-8859-1");

				// 文件名外的双引号处理firefox的空格截断问题
				response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", outPath));
				response.setContentType("application/x-msdownload");
				response.setCharacterEncoding("UTF-8");
				response.setHeader("Content-Disposition", "attachment;filename=" + outPath);

				String picLeftFile = session.getServletContext().getInitParameter("img_path");
				String picPath=picLeftFile;
				String moviePath=SystemConfigUtils.getSysConfig("movie_upload_path");
				String ttHeml=picLeftFile+"content.html";
				ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
				out.setEncoding("GBK");
				for(int i=0;i<list.size();i++){
					//DeCompressUtil.zip(out, new File(outPath), File.separator+list.get(i).getF_cc_name());
					//DeCompressUtil.zip(out, new File(picPath+list.get(i).getF_cc_picurl()), File.separator+list.get(i).getF_cc_name()+File.separator+"pic");
					if(list.get(i).getF_cc_transcodePath()!=null&&!"".equals(list.get(i).getF_cc_transcodePath())&&new File(moviePath+list.get(i).getF_cc_transcodePath()).exists()&&new File(moviePath+list.get(i).getF_cc_transcodePath()).isFile()){
						DeCompressUtil.zip(out, new File(moviePath+list.get(i).getF_cc_transcodePath()), File.separator+list.get(i).getF_cc_name()+File.separator+"mov");
					}
					String html=new String(getFileStream(ttHeml));
					html=html.replace("ThisCotnentName", list.get(i).getF_cc_name());
					if(list.get(i).getF_cc_picurl()!=null&&!"".equals(list.get(i).getF_cc_picurl())){
						if(list.get(i).getF_cc_picurl().indexOf(",")>0){
							String[] pics=list.get(i).getF_cc_picurl().split(",");
							String[] picNs=list.get(i).getF_cc_cprname().split(",");
							String picStr="";
							for(int j=0;j<pics.length;j++){
								picStr+=(picNs[j]+"<br/><img src='"+getPicBease(picPath+pics[j])+"'/><br/>");
							}
							html=html.replace("ThisPictureSrc", picStr);
						}else{
							html=html.replace("ThisPictureSrc", "<img src='"+getPicBease(picPath+list.get(i).getF_cc_picurl())+"'/>");
						}
					}else{
						html=html.replace("ThisPictureSrc", "");
					}
					String desc=stringChangeList(list.get(i).getF_cc_desc());
					html=html.replace("ThisIsTextINDIV", desc);
					out.putNextEntry(new ZipEntry(File.separator+list.get(i).getF_cc_name()+File.separator+"content.html"));
					out.write(html.getBytes(), 0, html.getBytes().length);
				}
				out.flush();
				out.close();
			}catch(Exception e){
				LOG.error("下载异常",e);
			}
		}


	}
	public static byte[] getFileStream(String file) throws UnsupportedEncodingException{
		String testText=file;
		InputStream in=null;
		byte[] data=null;
		if(fileCheck(testText,testText)){
			try{
				in=new FileInputStream(testText);
				data=new byte[in.available()];
				in.read(data);
			}catch(Exception e){
				e.printStackTrace();
			}finally {
				if(in!=null){
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return data;
		}else {
			return null;
		}


	}
	public static String getPicBease(String picUrl) throws UnsupportedEncodingException{
		System.out.println(picUrl);
		Locale.setDefault(Locale.ENGLISH);
		String beasePic="";
		if(picUrl.startsWith("http://")){
			beasePic=new String(Base64.encodeBase64(getImageFromNetByUrl(picUrl)), "UTF-8");
		}else{
			if(new File(picUrl).exists()){
				beasePic=new String(Base64.encodeBase64(getFileStream(picUrl)), "UTF-8");
			}else{
				return beasePic;
			}
		}
		if(picUrl.toUpperCase(Locale.ENGLISH).endsWith("JPG")){
			beasePic="data:image/jpeg;base64,"+beasePic;
		}
		if(picUrl.toUpperCase(Locale.ENGLISH).endsWith("PNG")){
			beasePic="data:image/png;base64,"+beasePic;
		}
		if(picUrl.toUpperCase(Locale.ENGLISH).endsWith("gif")){
			beasePic="data:image/gif;base64,"+beasePic;
		}
		return beasePic;
	}
	public static void main(String[] args) {
		try {
			String x=getPicBease("F:\\back.ed58e058.jpg");
			System.out.println(x);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static String stringChangeList(String str) throws Exception{
		Pattern pattern = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
		Matcher matcher = pattern.matcher(str);
		while(matcher.find()){
			String url=matcher.group();
			url=url.substring(5,url.length()-1);
			String s=getPicBease(url);
			if(s!=null&&s!=""){
				str=str.replace(url, s);
			}
		}
		return str;
	}
	public static byte[] getImageFromNetByUrl(String strUrl){
		System.out.println(strUrl);
		InputStream inStream = null;
		try {
			URL url = new URL(strUrl);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "image/jpeg");
			conn.setConnectTimeout(1 * 1000);
			inStream = conn.getInputStream();//通过输入流获取图片数据
			byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
			return btImg;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
				}
			}
		}
		return null;
	}
	/**
	 * 从输入流中获取数据
	 * @param inStream 输入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len=inStream.read(buffer)) != -1){
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
	public Map<String,Object> batchReviewContent(String ids) {
		Map<String,Object> resultMap = new HashMap<String, Object>();
		String[] idsArr = ids.split(",");
		int flag = 0;
		for(int i=0;i<idsArr.length;i++) {
			CmContentVo content = contentDao.selectContent(Integer.valueOf(idsArr[i]));
			if(content.getF_cc_transcodeFlag()==1){
				content.setF_cc_status(1);
			}else{
				content.setF_cc_status(1);
			}
			flag += contentDao.reviewContent(content);
		}
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","批量审核成功!处理"+flag+"条");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","批量审核失败!flag="+flag);
		}
		return resultMap;
	}
}